//
//  NSDictionary+SLAdd.m
//  shunlianPower2
//
//  Created by lengain on 2019/10/10.
//  Copyright © 2019 顺联网络. All rights reserved.
//

#import "NSDictionary+SLAdd.h"
#import "NSArray+SLAdd.h"
#import "SLCategoriesRuntime.h"


@implementation NSDictionary (SLAdd)

static NSString *SLDictionaryEmptyString = @"";

+ (void)load {
    Class myClass = objc_getClass("__NSDictionaryI");
    SLExchangeImplementations(myClass, @selector(objectForKey:), @selector(cm_objectForKey:));
}

- (id)cm_objectForKey:(id)aKey{
    
    if (!aKey) {
        return nil;
    }
    id obj = [self cm_objectForKey:aKey];
    return obj;
}

- (NSDictionary *)sl_judegNull{
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (NSString *key in [self allKeys]) {
        
        NSString *className =NSStringFromClass([[self objectForKey:key] class]);
        NSLog(@" ------- %@",className);//NSDictionary
        if ([className rangeOfString:@"NSDictionary"].location != NSNotFound ||[[self objectForKey:key] class] == [NSDictionary class]) {
            
            NSDictionary *tmp =  [self objectForKey:key];
        
            NSDictionary *tmpDic = [tmp sl_judegNull];
            if (tmpDic != nil) {
                [dic setObject:tmpDic forKey:key];
            }
        }else if([className rangeOfString:@"NSArray"].location != NSNotFound||[[self objectForKey:key] class] == [NSDictionary class]){
            
            NSArray *arrya = [self objectForKey:key];
            NSArray *tmpArray = [(NSArray *)self sl_judegNull:arrya];
            if (tmpArray != nil) {
                [dic setObject:tmpArray forKey:key];
            }
            
            
        }else if([className rangeOfString:@"String"].location != NSNotFound||[className rangeOfString:@"Number"].location != NSNotFound){
            NSString *value = [NSString stringWithFormat:@"%@",[self objectForKey:key]];
            
            if (![value isEqualToString:@"<null>"] && ![value isEqualToString:@"(null)"]) {
                NSString *value = [NSString stringWithFormat:@"%@",[self objectForKey:key]];
                [dic setObject:value forKey:key];
            }
        }else{
            //不是数组 不是字典 不是字符串 不是数字 -----暂不处理
        }
        
        
    }
    if ([dic allKeys].count ==0) {
        return nil;
    }
    return dic;
}

#ifdef DEBUG

- (NSString*)description {
    return [self sl_descriptionWithLevel:1];
}

- (NSString*)sl_descriptionWithLocale:(nullable id)locale {
    return [self sl_descriptionWithLevel:1];
}
- (NSString*)sl_descriptionWithLocale:(nullable id)locale indent:(NSUInteger)level {
    return [self sl_descriptionWithLevel:(int)level];
}

/**
 * 非字典时，会引发崩溃
 */
- (NSString*)sl_getUTF8String {
    if ([self isKindOfClass:[NSDictionary class]] ==NO) {
        return @"";
    }
    NSError *error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
    if (error) {
        return @"";
    }
    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return str;
}


- (NSString*)sl_descriptionWithLevel:(int)level {
    NSString *subSpace = [self sl_getSpaceWithLevel:level];
    NSString *space = [self sl_getSpaceWithLevel:level -1];
    NSMutableString *retString = [[NSMutableString alloc]init];
    // 1、添加 {
    [retString appendString:[NSString stringWithFormat:@"{"]];
    // 2、添加 key : value;
    [self enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[NSString class]]) {
            NSString *value = (NSString*)obj;
            value = [value stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString *subString = [NSString stringWithFormat:@"\n%@\"%@\" : \"%@\",", subSpace, key, value];
            [retString appendString:subString];
        }else if ([obj isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = (NSDictionary*)obj;
            NSString *str = [dic sl_descriptionWithLevel:level +1];
            str = [NSString stringWithFormat:@"\n%@\"%@\" : %@,", subSpace, key, str];
            [retString appendString:str];
        }else if ([obj isKindOfClass:[NSArray class]]) {
            NSArray *arr = (NSArray*)obj;
            NSString *str = [arr sl_descriptionWithLocale:nil indent:level + 1];
            str = [NSString stringWithFormat:@"\n%@\"%@\" : %@,", subSpace, key, str];
            [retString appendString:str];
        }else {
            NSString *subString = [NSString stringWithFormat:@"\n%@\"%@\" : %@,", subSpace, key, obj];
            [retString appendString:subString];
        }
    }];
    if ([retString hasSuffix:@","]) {
        [retString deleteCharactersInRange:NSMakeRange(retString.length-1,1)];
    }
    // 3、添加 }
    [retString appendString:[NSString stringWithFormat:@"\n%@}", space]];
    return retString;
}


- (NSString*)sl_getSpaceWithLevel:(int)level {
    NSMutableString *mustr = [[NSMutableString alloc]init];
    for (int i=0; i<level; i++) {
        [mustr appendString:@"\t"];
    }
    return mustr;
}

#endif


- (NSString *)stringValueOrEmptyStringForKey:(NSString *)key {
    if (!key) return SLDictionaryEmptyString;
    id value = self[key];
    if (!value || value == [NSNull null]) return SLDictionaryEmptyString;
    if ([value isKindOfClass:[NSString class]]) return value;
    if ([value isKindOfClass:[NSNumber class]]) return ((NSNumber *)value).description;
    return SLDictionaryEmptyString;
}

- (nullable NSArray *)arrayValueOrNilForKey:(NSString *)key {
    return [self arrayValueForKey:key default:nil];
}

- (nullable NSArray *)arrayValueForKey:(NSString *)key default:(nullable NSArray *)def {
    if (!key) return def;
    id value = self[key];
    if (!value || value == [NSNull null]) return def;
    if ([value isKindOfClass:[NSArray class]]) return value;
    return def;
}

- (nullable NSDictionary *)dictionaryValueOrNilForKey:(NSString *)key {
    return [self dictionaryValueForKey:key default:nil];
}

- (nullable NSDictionary *)dictionaryValueForKey:(NSString *)key default:(nullable NSDictionary *)def {
    if (!key) return def;
    id value = self[key];
    if (!value || value == [NSNull null]) return def;
    if ([value isKindOfClass:[NSDictionary class]]) return value;
    return def;
}

@end
